package com.agileai.esb.smc.controller.sersta;

import java.util.List;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.sersta.ServiceInfomationSelect;
import com.agileai.esb.smc.bizmoduler.sersta.SysInfomation8ContentManage;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.PickFillModelHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

public class ServiceInfomationSelectHandler
        extends PickFillModelHandler {
    public ServiceInfomationSelectHandler() {
        super();
        this.serviceId = buildServiceId(ServiceInfomationSelect.class);
    }
    
    protected void processPageAttributes(DataParam param) {
    	SysInfomation8ContentManage sysInfomation8ContentManage = this.lookupService(SysInfomation8ContentManage.class);
    	List<DataRow> appList = sysInfomation8ContentManage.queryAppProjectRecords();
		FormSelect formSelect = new FormSelect();
		formSelect.setKeyColumnName("APP_ID");
		formSelect.setValueColumnName("APP_NAME");
		formSelect.putValues(appList);
		setAttribute("appName",formSelect.addSelectedValue(param.get("appName")));
    }

    protected void initParameters(DataParam param) {
        initParamItem(param, "serviceName", "");
        initParamItem(param, "serviceCode", "");
        initParamItem(param, "appName", "");
    }

    protected ServiceInfomationSelect getService() {
        return (ServiceInfomationSelect) this.lookupService(this.getServiceId());
    }
    
    @PageAction
    public ViewRenderer addService(DataParam param){
    	String responseText = FAIL;
    	try {
    		String ids = param.getString("ids");
        	String sysinfoId = param.getString("SYSINFO_ID");
        	SysInfomation8ContentManage sysInfomation8ContentManage = this.lookupService(SysInfomation8ContentManage.class);
        	List<DataRow> records = sysInfomation8ContentManage.findServiceRecordsBySysinfoId(param);
        	int count = records.size();
        	if(!"".equals(ids)){
        		String[] idArray = ids.split(",");
        		for (int i = 0; i < idArray.length; i++) {
        			String id = idArray[i];
        			String rsrId = KeyGenerator.instance().genKey();  
        			DataParam dataParam = new DataParam("RSR_ID",rsrId,"SYSINFO_ID",sysinfoId,"SERVICE_ID",id,"RSR_SORT",count+i+1);
        			sysInfomation8ContentManage.addService(dataParam);
    			}
        	}
        	responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
}
